package com.sx.netty.nio.Demo02_GroupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @Author ShuXin
 * @Description 群聊系统服务端
 * @Date 2020/11/5 15:34
 */

public class GroupChatServer {
    //    定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //    构造器，初始化服务
    public GroupChatServer() {
//            开启一个selector
        try {
            selector = Selector.open();
//            获取一个SocketServerChannel
            listenChannel = ServerSocketChannel.open();
//            绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
//            设置非阻塞模式
            listenChannel.configureBlocking(false);
//            将listenChannel注册到selector上
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    监听
    public void listen() {
        try {
//            进行循环处理
            while (true) {
                int count = selector.select();
                if (count > 0) {//有事件要进行处理
//                    遍历获取selectionKey的集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
//                        取出selectionKey
                        SelectionKey key = iterator.next();
//                        进行监听，如果连接上
                        if (key.isAcceptable()) {
                            SocketChannel channel = listenChannel.accept();
                            channel.configureBlocking(false);
//                            将该channel注册到selector上,并绑定事件
                            channel.register(selector, SelectionKey.OP_READ);
//                            提示
                            System.out.println(channel.getLocalAddress().toString().substring(1) + "上线");
                        }
                        if (key.isReadable()) {//通道发送read事件，即通道可以进行读
//                            处理读事件
                            readDate(key);
                        }
//                        处理过后，手动删除
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待中...");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            发生异常进行处理
        }
    }

    //    读取客户端发送的消息
    private void readDate(SelectionKey key) {
//        获取关联的channel
        SocketChannel channel = null;
//        创建
        try {
//         获取channel
            channel = (SocketChannel) key.channel();
//            创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
//            从buffer中读取数据
            int count = channel.read(buffer);
//            判断count
            if (count > 0) {
//                将缓冲区的数据抓换成字符串
                String msg = new String(buffer.array());
//                输出客户端发送的信息
                System.out.println("from客户端：\t" + channel.getRemoteAddress().toString().substring(16) + msg);
//                想其他客户端转发此条消息
                sendInfoToOther(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线了");
//                取消注册
                key.cancel();
//                关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    public void sendInfoToOther(String msg, SocketChannel self) throws IOException {
        System.out.println("消息服务转发中...");
//        遍历所有注册到selector上的SocketChannel，并排除自己
        for (SelectionKey key : selector.keys()) {
//            获取对应channel
            Channel channel = key.channel();
//            排除自己
            if (channel instanceof SocketChannel && channel != self) {
//                进行转型
                SocketChannel dest = (SocketChannel) channel;
//                将消息转储到的buffer中
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//                将buffer中的内容写入通道中
                dest.write(buffer);
            }
        }
    }

    //    创建服务器对象
    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
//        调用监听方法实施监听
        server.listen();
    }
}
